/*
 * 文件名：OutLawyerController.java
 * 版权：Copyright by www.infopub.top
 * 描述：
 * 修改人：wangw
 * 修改时间：2020年3月30日
 * 跟踪单号：
 * 修改单号：
 * 修改内容：
 */

package top.infopub.mgr.la.web;


import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import top.infopub.mgr.common.page.ParamPage;
import top.infopub.mgr.common.vo.ErrorCodeEnum;
import top.infopub.mgr.common.vo.RspVo;
import top.infopub.mgr.flow.web.GenericFlowController;
import top.infopub.mgr.hr.service.StaffInfoService;
import top.infopub.mgr.la.domain.OutLawyerDomain;
import top.infopub.mgr.la.service.OutLawyerService;
import top.infopub.mgr.la.vo.OutLawyerVo;
import top.infopub.mgr.mkt.service.DiscloseProService;
import top.infopub.mgr.util.FileHelper;
import top.infopub.mgr.util.LogUtil;
import top.infopub.mgr.util.LogUtil.AcctionType;
import top.infopub.mgr.util.LogUtil.LogModelType;
import top.infopub.model.hr.StaffInfo;
import top.infopub.model.la.OutLawyerAtt;
import top.infopub.security.util.SessionUserUtils;
import top.infopub.security.vo.AuthorizationVO;
import top.infopub.tdp.sys.service.CodeGeneratorConfigService;
import top.infopub.util.IdFactory;

import com.github.pagehelper.Page;


/**
 * 外聘律师
 * @author wangw
 * @version 2020年3月30日
 * @see OutLawyerController
 * @since
 */
@Controller
@RequestMapping("/outLawyer")
public class OutLawyerController extends GenericFlowController {

    @Autowired
    private CodeGeneratorConfigService codeGeneratorConfigService;

    @Autowired
    private StaffInfoService staffInfoService;

    @Autowired
    private DiscloseProService discloseProService;

    @Autowired
    private OutLawyerService outLawyerService;

    /**
     * 外聘律师列表
     * @return
     */
    @RequestMapping("/list")
    public String list() {
        return "la/lay-outLawyer-list";
    }

    /**
     * 外聘律师列表数据
     * @return
     */
    @RequestMapping("/queryDataByCondition")
    @ResponseBody
    public RspVo<OutLawyerDomain> queryDataByCondition(OutLawyerVo outLawyerVo,
                                                        ParamPage paramPage) {
        Page<OutLawyerDomain> page = new Page<OutLawyerDomain>();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        //查询时，结束日期增加一天
        if (outLawyerVo.getEndDate() != null) {
            outLawyerVo.setEndDate(DateUtils.addDays(outLawyerVo.getEndDate(), 1));
        }
        page = outLawyerService.selectByDomainWhere(page, outLawyerVo);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }

    /**
     * 外聘律师-我审批的列表数据
     * @return
     */
    @RequestMapping("/queryMyCheckDataByCondition")
    @ResponseBody
    public RspVo<OutLawyerDomain> queryMyCheckDataByCondition(OutLawyerVo outLawyerVo,
                                                               ParamPage paramPage) {
        Page<OutLawyerDomain> page = new Page<OutLawyerDomain>();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        //查询时，结束日期增加一天
        if (outLawyerVo.getEndDate() != null) {
            outLawyerVo.setEndDate(DateUtils.addDays(outLawyerVo.getEndDate(), 1));
        }
        outLawyerVo.setAddBy(SessionUserUtils.getSessionUserId());
        page = outLawyerService.selectMyCheckByDomainWhere(page, outLawyerVo);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }

    /**
     * 外聘律师-新增
     * @return
     */
    @RequestMapping("/add")
    public String add(HttpServletRequest request) {
        AuthorizationVO authorizationVO = SessionUserUtils.getSessionAttributeForUserDtl();
        StaffInfo staffInfo = staffInfoService.selectByPrimaryKey(authorizationVO.getHrStaffId());
        request.setAttribute("staffName", staffInfo.getStaffName());
        return "la/lay-outLawyer-add";
    }

    /**
     * 根据id查询外聘律师详情  > 注意：方法命名必须为：toDealOrDetail
     * @param id 外聘律师Id
     * @return
     * @see
     */
    @RequestMapping("/toDealOrDetail")
    public ModelAndView queryById(HttpServletRequest request, String id, String processDealWith) {
        Map<String, Object> map = new HashMap<String, Object>();
        OutLawyerVo outLawyer = outLawyerService.queryById(id);
        map.put("outLawyer", outLawyer);
        // 审批flag
        request.setAttribute("processDealWith", processDealWith);
        // 审批data
        processData(request, outLawyer.getProcessId());
        return new ModelAndView("la/lay-outLawyer-detail", map);
    }

    /**
     * 新增外聘律师
     * @return
     */
    @SuppressWarnings({"rawtypes"})
    @RequestMapping("/save")
    public @ResponseBody RspVo save(HttpServletRequest request,OutLawyerVo outLawyer) {
        String[] fileAtt = request.getParameterValues("fileAtt");
        //外聘律师表处理
        AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();
        String id = IdFactory.getUUIDUpper();
        outLawyer.setId(id);
        outLawyer.setAddBy(vo.getId());
        outLawyer.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
        String code = codeGeneratorConfigService.generatorCode("la_out_lawyer");
        outLawyer.setCodes(code);
        // 处理processId
        outLawyer.setProcessId(IdFactory.getUUIDUpper());
        outLawyer.setProcessStatus("1");//审批中
        outLawyer.setUptBy(vo.getId());
        outLawyer.setUptTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());

        //上传附件
        List<OutLawyerAtt> outLawyerAtts = new ArrayList<OutLawyerAtt>();
        //附件材料
        if (fileAtt != null) {
            for (String file : fileAtt) {
                OutLawyerAtt outLawyerAtt = createFileAtt(vo, id, file);
                outLawyerAtts.add(outLawyerAtt);
            }
        }
        outLawyerService.saveOutLawyer(outLawyer, outLawyerAtts);
        LogUtil.bizLog(LogModelType.OTHER, AcctionType.ADD, "法务管理 -外聘律师：申请人=" + outLawyer.getStaffName(), null);
        return RspVo.getSuccessResponse();
    }

    private OutLawyerAtt createFileAtt(AuthorizationVO vo, String outLawyerId, String file) {
        //资料信息数组
        String[] fileAttStr = file.split("\\|");
        OutLawyerAtt fileAtt = new OutLawyerAtt();
        fileAtt.setId(fileAttStr[1]);
        fileAtt.setTypes("1");
        fileAtt.setOutLawyerId(outLawyerId);//项目id
        String fileName = fileAttStr[0].substring(0, fileAttStr[0].lastIndexOf("."));
        String suffix = fileAttStr[0].substring(fileAttStr[0].lastIndexOf("."),
            fileAttStr[0].length()).toLowerCase();//后缀转小写
        fileAtt.setFileName(fileName);//文件名
        fileAtt.setFileSuffix(suffix);//文件后缀
        fileAtt.setFilePath(fileAttStr[2]);//文件保存路径
        fileAtt.setAddBy(vo.getId());//添加人
        fileAtt.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());//添加时间
        return fileAtt;
    }

    /**
     * 上传附件
     * @param request
     * @param response
     * @return 
     * @throws IOException 
     * @see
     */
    @SuppressWarnings("rawtypes")
    @RequestMapping("/uploadAtt")
    public @ResponseBody RspVo uploadAtt(HttpServletRequest request)
        throws IOException {
        List<String> returnFileStrList = new ArrayList<>();
        MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest)request;
        Map<String, MultipartFile> map = multipartHttpServletRequest.getFileMap();
        if (map != null) {
            for (String name : map.keySet()) {
                MultipartFile file = map.get(name);
                if (file == null) {
                    return ErrorCodeEnum.ERROR_COMMON_PARAM.getRspVo("上传文件不能为空");
                }
                // 上传文件
                String fileId = IdFactory.getUUIDSerialNumber();
                // 服务器资源路径
                String serverPath = "outLawyerAtt";
                String filePath = FileHelper.upload(file, serverPath);
                returnFileStrList.add(file.getOriginalFilename().trim() + "|"
                                      + fileId + "|" + filePath);
                LogUtil.bizLog(LogModelType.PROJECT, AcctionType.ADD, "上传附件-文件名:" + filePath
                                                                      + "，文件路径:" + filePath, null);
            }
        }
        return RspVo.getSuccessResponse(returnFileStrList);
    }

}
